//
//  StatusListViewModel.m
//  kuangjia
//
//  Created by 张帅 on 15/10/1.
//  Copyright © 2015年 ZhangShuai. All rights reserved.
//

#import "StatusListViewModel.h"
#import "Status.h"
#import <SDWebImageManager.h>
#import "StatusDAL.h"
typedef  void(^finishedBlock)();

@interface StatusListViewModel ()


@end

@implementation StatusListViewModel


-(NSMutableArray *)statuses{

    if (_statuses==nil) {
        _statuses=[NSMutableArray array];
    }
    return _statuses;
}


-(RACSignal*)loadStatusesWithPullupRefresh:(BOOL)isPullupRefresh{
    

    NSInteger since_id  = (self.statuses.count) == 0 ? 0 : [self.statuses.firstObject status].id;
//    int since_id =0;
   
    NSInteger max_id =0;
    
    if (isPullupRefresh) {
        
        since_id=0;
        
        StatusViewModel*viewModel = self.statuses.lastObject;
        
        Status *model =viewModel.status;
        
        max_id = model.id;
       
    }
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber>subscriber) {
        
     [StatusDAL loadStatusSince_id:since_id max_id:max_id completionBlock:^(NSArray *array) {
         // 1. 获取 result 中的 statuses 字典数组

         
         if (array==nil) {
             [subscriber sendError:[NSError errorWithDomain:@"com.itheima.error" code:-1002 userInfo:@{@"error message":@"没有正确的数组"}]];
             return ;
         }
         
         
         // 2. 字典转模型
         // 定义并且创建一个临时数组，记录当前网络请求返回的结果
         NSMutableArray *arrayM=[NSMutableArray array];
         
         for (NSDictionary *dict in array) {
             //
        StatusViewModel * stausModle = [[StatusViewModel alloc] initWithStatus:[[Status alloc] initWtihDict:dict]];
        
             [arrayM addObject:stausModle];
        }
         
         NSLog(@"刷新到%lu条微博",(unsigned long)arrayM.count);
             
        typeof(self) wself =self;
         
         [self cacheWebImage:arrayM finished:^{
      
                             NSMutableArray *tmpM =[NSMutableArray array];
             
                             if (since_id!=0) {
                                 [tmpM addObjectsFromArray:arrayM];
                                 [tmpM addObjectsFromArray:wself.statuses];
                                 wself.statuses = tmpM;
                             }else if (max_id!=0){
             
                                 [self.statuses addObjectsFromArray:arrayM];
             
                             }else{
                                 self.statuses=arrayM;
                             }
             
             
                             [subscriber sendNext:@(arrayM.count)];
             
                             [subscriber sendCompleted];
             
             
         }];

             
     }];
        
        return nil;
    }];


}


- (void)cacheWebImage:(NSMutableArray*)statusViewModel finished:(finishedBlock) finished{
 
  // 1. 定义调度组
    
    dispatch_group_t group = dispatch_group_create();
    
      // 遍历视图模型数组
    
    __block   NSInteger dataLength =  0;
    
    // 记录图像大 小
    for (StatusViewModel *vieModel in statusViewModel) {
          // 目标：只需要缓存单张图片
        
        if (!vieModel.thumbnailURLs) {
            return;
        }
        
        if (vieModel.thumbnailURLs.count!=1) {
            continue;
        }
        
        NSLog(@"StatusListViewModel---%@",vieModel.thumbnailURLs);
        dispatch_group_enter(group);
      
        [[SDWebImageManager sharedManager] downloadImageWithURL:vieModel.thumbnailURLs[0] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            // 代码执行到此，图片已经缓存完成，不一定有 image

            if (image!=nil) {
                
                NSData *data =  UIImagePNGRepresentation(image);
                dataLength +=data.length;
            }
            
            //出组
            dispatch_group_leave(group);
            
        
        }];
        
    }
    
    //完成调度监听
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    
        NSLog(@"缓存图像%ld k",dataLength/1024 );
        
        finished();
    });
}

//        [[[NetworkTools sharedTools] loadStatussince_id:since_id max_id:max_id] subscribeNext:^(id result) {
//            //     1. 获取 result 中的 statuses 字典数组
//
//            NSMutableArray *array = result[@"statuses"];
//
//
//            if (!array) {
////                NSLog(@"没有正确的数据 %@",array);
//                return ;
//            }
//
//             NSMutableArray* arrayM = [NSMutableArray  array];
//
//            for (NSDictionary *dict in array) {
//
//                StatusViewModel * stausModle = [[StatusViewModel alloc] initWithStatus:[[Status alloc] initWtihDict:dict]];
//                [arrayM addObject:stausModle];
//            }
////
//            NSLog(@"刷新到%lu条微博",(unsigned long)arrayM.count);
//
//            typeof(self) wself =self;
//
//            [self cacheWebImage:arrayM finished:^{
//
//                //
//                NSMutableArray *tmpM =[NSMutableArray array];
//
//                if (since_id!=0) {
//                    [tmpM addObjectsFromArray:arrayM];
//                    [tmpM addObjectsFromArray:wself.statuses];
//                    wself.statuses = tmpM;
//                }else if (max_id!=0){
//
//                    [self.statuses addObjectsFromArray:arrayM];
//
//                }else{
//                    self.statuses=arrayM;
//                }
//
//
//                [subscriber sendNext:@(arrayM.count)];
//
//                [subscriber sendCompleted];
//
//            } ];
//
//
//
//        } error:^(NSError *error) {
//
//            NSLog( @"StatusListViewModel---error%@",error);
//        } completed:^{
//
//            NSLog(@"完成");
//        }];

@end
